package com.fly.demo.job;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.util.Assert;

import com.fly.demo.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class TaskJob
{
    @Value("${welcome.message:hello, 00fly in java!}")
    String msg;
    
    @Autowired
    UserService userService;
    
    @Scheduled(fixedDelay = 1000L * 60)
    public void retrieveCountry()
    {
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < 5; i++)
        {
            map.put(RandomStringUtils.randomNumeric(5), RandomStringUtils.randomAlphabetic(5));
        }
        log.info("{}", userService.queryOldUsers(map));
    }
    
    /**
     * 测试日志打印
     */
    @Scheduled(fixedRate = 5000)
    public void run()
    {
        log.trace("★★★★★★★★ {}", msg);
        log.debug("★★★★★★★★ {}", msg);
        log.info("★★★★★★★★ {}", msg);
        log.warn("★★★★★★★★ {}", msg);
        printError();
    }
    
    private void printError()
    {
        try
        {
            if (RandomUtils.nextInt(1, 20) == 1)
            {
                int i = 1 / 0; // 抛出异常
                Assert.isNull(i, "The value must be null");
            }
        }
        catch (Exception e)
        {
            log.error("系统出错：" + e.getMessage(), e);
        }
    }
    
    @Bean
    ScheduledExecutorService scheduledExecutorService()
    {
        // return Executors.newScheduledThreadPool(8);
        return new ScheduledThreadPoolExecutor(8, new CustomizableThreadFactory("schedule-pool-"));
    }
}
